package com.allwees.bs.c.module.user.repository;

import com.allwees.bs.c.module.base.repository.BaseRepository;
import com.allwees.bs.c.module.user.entity.ShippingAddressEntity;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface ShippingAddressRepository extends BaseRepository<ShippingAddressEntity, Integer> {

    /**
     * 获取用户所有收货地址
     *
     * @param userUuid 用户ID
     * @return 收货地址列表
     */
    @Query("SELECT s FROM ShippingAddressEntity s WHERE s.userUuid = :userUuid AND s.isDeleted = 0 ORDER BY s.createdAt DESC")
    List<ShippingAddressEntity> findUserAllShippingAddress(@Param("userUuid") String userUuid);

    /**
     * 获取默认收货地址
     *
     * @param userUuid 用户ID
     * @return 默认收货地址
     */
    @Query("SELECT s FROM ShippingAddressEntity s WHERE s.userUuid = :userUuid AND s.isDeleted = 0 AND s.isDefault = 1")
    ShippingAddressEntity findDefaultShippingAddress(@Param("userUuid") String userUuid);


    /**
     * 将指定用户所有默认收货地址改为非默认
     * @param userUuid 用户ID
     */
    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(value = "UPDATE usr_shipping_address s SET s.is_default = 0 WHERE s.user_uuid = ?1 AND s.is_default = 1", nativeQuery = true)
    void changeDefault2NoN(String userUuid);

    @Query("SELECT s FROM ShippingAddressEntity s WHERE s.uuid = :uuid AND s.isDeleted = 0")
    ShippingAddressEntity getByUuid(@Param("uuid") String uuid);

    List<ShippingAddressEntity> findAllByUserUuid(String userUuid);
}
